package com.gzy.mylog.server;

import com.gzy.mylog.model.User;
import com.gzy.mylog.repository.UserRepository;
import com.gzy.mylog.security.SecurityConfig;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class AuthServer {

    @Autowired
    UserRepository userRepository;

    public List<User> loadAll() {
        return userRepository.findAll();
    }

    public String login(String username, String password) {
        var user = getUserByUsername(username);
        if (!Objects.equals(user.getPassword(),password)) {
            throw new RuntimeException("密码不正确");
        }
        JwtBuilder builder = Jwts.builder() //这里其实就是new一个JwtBuilder，设置jwt的body
                .setSubject(user.getId()+"")          //iat: jwt的签发时间
                .signWith(SignatureAlgorithm.HS256, SecurityConfig.KEY);//设置签名使用的签名算法和签名使用的秘钥

        String jwt = builder.compact();

        return jwt;
    }

    public User checkJWT(String jwt){
        Jws<Claims> claimsJws = Jwts.parser()  //得到DefaultJwtParser
                .setSigningKey(SecurityConfig.KEY)         //设置签名的秘钥
                .parseClaimsJws(jwt);
        String subject = claimsJws.getBody().getSubject();

        Optional<User> byId = userRepository.findById(Long.parseLong(subject));
        if (byId.isEmpty()){
            throw new RuntimeException("找不到用户2");
        }

        if (byId.get().getDeleteAt() != null) {
            throw new RuntimeException("用户不存在2");
        }

        return byId.get();
    }

    public User getUserByUsername(String username) {
        User user = userRepository.findUserByUsername(username);
        if (user == null){
            throw new RuntimeException("找不到用户");
        }

        return user;
    }

    public void signup(String username, String password) {

        User temp = userRepository.findUserByUsername(username);

        if (temp != null){
            throw new RuntimeException("用户已存在");
        }

        User user = new User();

        user.setUsername(username);
        user.setPassword(password);

        user.setCreateAt(System.currentTimeMillis());
        user.setRole("USER");

        user.setAvatar("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598594771694&di=bb59fb2200538918dff875283b1beb2d&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201802%2F07%2F20180207204747_ixGsL.thumb.700_0.jpeg");

        userRepository.save(user);
    }
}
